package com.xuzz.study.thread.lock;

public class ReadWriteLock {
    private int reads = 0 ;
    private int writes = 0 ;
    private int writeRequests = 0 ;
    public synchronized void lockRead()
            throws InterruptedException
    {
        //读读不阻塞
        //读写阻塞。
        //所以，读锁只需要判断是否有写正在进行
        while(writes>0 || writeRequests>0)
        {
            wait();
        }
        reads++;
    }

    public synchronized void unlockRead()
            throws InterruptedException
    {
        reads--;
        notifyAll();
    }

    public synchronized void lockWrite()
            throws InterruptedException
    {
        writeRequests++;
        //写读阻塞、写写阻塞
        while(reads>0 || writes>0)
        {
            wait();
        }
        writeRequests--;
        writes++;
    }

    public synchronized void unlockWrite()
            throws InterruptedException
    {
        writes--;
        notifyAll();
    }
}
